<template>
  <el-form :model="editForm" :rules="rules" label-width="135px" ref="editFormRef">
    <div class="bg-white my-[10px]">
      <BaseHead>申请人信息</BaseHead>
      <div class="p-[10px]">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="申请人" prop="applierName">
              <el-input v-model="editForm.applierName" placeholder="申请人" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <CommonRadio
                :isFetch="false"
                :dataList="sexList"
                v-model="editForm.sex"
                valueKey="code"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生年月" prop="birthday">
              <el-date-picker
                v-model="editForm.birthday"
                type="month"
                clearable
                placeholder="请选择出生年月"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="行政职务" prop="executivePost">
              <CommonRadio
                :isFetch="false"
                :dataList="executivePostList"
                v-model="editForm.executivePost"
                valueKey="code"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请人学位" prop="applierEduDegreeId">
              <CommonRadio
                :isFetch="false"
                :dataList="applierEduDegreeList"
                v-model="editForm.applierEduDegreeId"
                valueKey="code"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请人职称" prop="applierTitleId">
              <CommonTreeSelect
                :isFetch="false"
                :dataList="applierTitleList"
                placeholder="申请人职称"
                v-model="editForm.applierTitleId"
                check-strictly
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在研究基地类型" prop="researchBaseType">
              <CommonSelect
                :isFetch="false"
                :dataList="researchBaseTypeList"
                placeholder="所在研究基地类型"
                v-model="editForm.researchBaseType"
                valueKey="code"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在研究基地名称" prop="researchBase">
              <el-input v-model="editForm.researchBase" placeholder="所在研究基地名称" clearable />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </div>
    <div class="bg-white">
      <BaseHead>项目信息</BaseHead>
      <div class="p-[10px]">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="项目名称" prop="name">
              <el-input v-model="editForm.name" placeholder="项目名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请经费" prop="applyFee">
              <el-input
                v-model="editForm.applyFee"
                placeholder="申请经费"
                clearable
                @input="fomateNumber(editForm, 'applyFee', $event)"
                @blur="applyFeeBlur"
              >
                <template #append>万元</template></el-input
              >
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目分类" prop="projectTypeId">
              <CommonTreeSelect
                :isFetch="false"
                :dataList="projectTypeList"
                placeholder="项目分类"
                v-model="editForm.projectTypeId"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="国民行业" prop="nationalIndustryCode">
              <CommonTreeSelect
                :isFetch="false"
                :dataList="nationalIndustryList"
                placeholder="国民行业"
                v-model="editForm.nationalIndustryCode"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="科技活动类型" prop="technologyActivityType">
              <CommonSelect
                placeholder="科技活动类型"
                :isFetch="false"
                :dataList="technologyActivityList"
                v-model="editForm.technologyActivityType"
                valueKey="code"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="研究开始日期" prop="planStartDate">
              <el-date-picker
                v-model="editForm.planStartDate"
                type="month"
                clearable
                placeholder="研究开始日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="研究结束日期" prop="planEndDate">
              <el-date-picker
                v-model="editForm.planEndDate"
                type="month"
                clearable
                placeholder="研究结束日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="一级学科" prop="subjectId">
              <CommonSelect
                placeholder="一级学科"
                v-model="editForm.subjectId"
                valueKey="id"
                labelKey="label"
                :isFetch="false"
                :dataList="subjectList"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属单位" prop="unitId">
              <CommonTreeSelect
                placeholder="所属单位"
                v-model="editForm.unitId"
                valueKey="codeColumn"
                labelKey="valueColumn"
                :isFetch="false"
                :dataList="unitList"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="项目摘要" prop="projectSummary">
              <el-input
                v-model="editForm.projectSummary"
                placeholder="项目摘要"
                clearable
                type="textarea"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="关键词" prop="keyword">
              <el-input
                v-model="editForm.keyword"
                placeholder="(不超过5个，用分号隔开)"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="申报书" prop="uploadFileId">
              <FileUpload :uploadUrl="uploadUrl" v-model="fileList" @change="fileChange" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="note">
              <el-input v-model="editForm.note" clearable type="textarea"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </div>
  </el-form>
</template>

<script setup>
import BaseHead from "@/views/project/components/BaseHead.vue";
import CommonRadio from "@/views/project/components/CommonRadio.vue";
import CommonSelect from "@/views/project/components/CommonSelect.vue";
import CommonTreeSelect from "@/views/project/components/CommonTreeSelect.vue";
import FileUpload from "@/views/project/components/FileUpload.vue";
import { sbProject, sbBaseDetail } from "@/api/project/xj/sbxm";
import { getPersonList } from "@/api/project/common";
import useUserStore from "@/store/modules/user";
import { formatDate } from "@/utils/formatTime";
import { assignObj, fomateNumber } from "@/utils/main";
import { keyWordReg } from "@/utils/validate";
import { ElMessage } from "element-plus";
const sexList = inject("sexList");
const executivePostList = inject("executivePostList");
const applierEduDegreeList = inject("applierEduDegreeList");
const applierTitleList = inject("applierTitleList");
const researchBaseTypeList = inject("researchBaseTypeList");
const projectTypeList = inject("projectTypeList");
const nationalIndustryList = inject("nationalIndustryList");
const technologyActivityList = inject("technologyActivityList");
const subjectList = inject("subjectList");
const unitList = inject("unitList");
const uploadUrl = `/commonFile/uploadFile?modelName=xjApply`;
const userStore = useUserStore();
const fileList = ref([]);
const editFormRef = ref();
const operateId = ref(null);
const baseInfoData = ref({});
const isAuditor = inject("isAuditor");
const taskId = inject("taskId");
const checkStatus = inject("checkStatus");
const lastApplyFee = ref(0); //未修改之前的总经费
const editForm = reactive({
  applyInfoId: "", //申报计划id
  applierId: "", //申请人id
  applierName: "",
  sex: "",
  birthday: "",
  executivePost: "", //行政职务
  applierEduDegreeId: "", //学位
  applierTitleId: "", //职称
  researchBaseType: "", //所在研究基地类型
  researchBase: "", //所在研究基地名称
  name: "", //项目名称
  applyFee: "", //申请经费
  projectTypeId: "", //上层列表页传递（项目分类code值）
  nationalIndustryCode: "", //国民经济行业
  technologyActivityType: "", //科技活动类型
  planStartDate: "", //研究开始日期
  planEndDate: "", //研究结束日期
  subjectId: "", //一级学科
  unitId: "", //所属单位
  projectSummary: "",
  keyword: "",
  uploadFileId: "",
  note: "",
});
//验证研究开始日期
const validatePlanStartDate = (rule, value, callback) => {
  if (editForm.planEndDate) {
    if (new Date(value).getTime() >= new Date(editForm.planEndDate).getTime()) {
      callback(new Error("研究开始日期必须早于研究结束日期"));
    } else {
      callback();
    }
  } else {
    callback();
  }
};
//验证研究结束日期
const validatePlanEndDate = (rule, value, callback) => {
  if (editForm.planStartDate) {
    if (new Date(value).getTime() <= new Date(editForm.planStartDate).getTime()) {
      callback(new Error("研究结束日期必须晚于研究开始日期"));
    } else {
      callback();
    }
  } else {
    callback();
  }
};
const rules = reactive({
  applierName: [
    {
      required: true,
      message: "申请人必填",
    },
  ],
  sex: [
    {
      required: true,
      message: "性别必填",
    },
  ],
  birthday: [
    {
      required: true,
      message: "出生年月必填",
    },
  ],
  executivePost: [
    {
      required: true,
      message: "行政职务必填",
    },
  ],
  applierEduDegreeId: [
    {
      required: true,
      message: "申请人学位必填",
    },
  ],
  applierTitleId: [
    {
      required: true,
      message: "申请人职称必填",
    },
  ],
  researchBaseType: [
    {
      required: true,
      message: "所在研究基地类型必填",
    },
  ],
  researchBase: [
    {
      required: true,
      message: "所在研究基地名称必填",
    },
  ],
  name: [
    {
      required: true,
      message: "项目名称必填",
    },
  ],
  applyFee: [
    {
      required: true,
      message: "申请经费必填",
    },
  ],
  projectTypeId: [
    {
      required: true,
      message: "项目分类必填",
    },
  ],
  nationalIndustryCode: [
    {
      required: true,
      message: "国民行业必填",
    },
  ],
  technologyActivityType: [
    {
      required: true,
      message: "科技活动类型必填",
    },
  ],
  planStartDate: [
    {
      required: true,
      message: "研究开始日期必填",
    },
    { validator: validatePlanStartDate, trigger: "blur" },
  ],
  planEndDate: [
    {
      required: true,
      message: "研究结束日期必填",
    },
    { validator: validatePlanEndDate, trigger: "blur" },
  ],
  subjectId: [
    {
      required: true,
      message: "一级学科必填",
    },
  ],
  unitId: [
    {
      required: true,
      message: "所属单位必填",
    },
  ],
  projectSummary: [
    {
      required: true,
      message: "项目摘要必填",
    },
  ],
  keyword: [
    {
      required: true,
      message: "关键词必填",
    },
    {
      pattern: keyWordReg,
      message: "关键词不超过5个，用分号隔开，不能以分号开头或结尾",
    },
  ],
  uploadFileId: [
    {
      required: true,
      message: "请上传申报书",
    },
  ],
});
//获取申报的基础信息
const getBaseInfoData = async () => {
  const params = {
    id: operateId.value,
  };
  try {
    const res = await sbBaseDetail(params);
    baseInfoData.value = res.data;
    lastApplyFee.value = res.data.applyFee;
    //附件列表赋值
    const files = res.data.fileInfo ? res.data.fileInfo : [];
    fileList.value = files.map((item) => {
      return {
        name: item.fileName,
        id: item.id,
      };
    });
  } catch (error) {
    console.log(error);
  }
};
const emit = defineEmits(["save-success", "save-ok"]);
//获取当前登录人信息
const getPersonInfo = async () => {
  const params = {
    id: userStore.userRealId,
  };
  try {
    const res = await getPersonList(params);
    const person = res.data[0];
    editForm.birthday = person.birthday;
    editForm.applierEduDegreeId = person.eduDegreeId;
    editForm.applierTitleId = person.titleId;
  } catch (error) {
    console.log(error);
  }
};
// 新增 applyInfoId:申报计划id projectTypeId:项目分类id
const add = async (applyInfoId, projectTypeId) => {
  operateId.value = null;
  //新增时申请人默认为登录用户
  editForm.applierId = userStore.userRealId;
  editForm.applierName = userStore.nickName;
  editForm.unitId = userStore.deptId;
  editForm.sex = userStore.sex;
  editForm.applyInfoId = applyInfoId;
  editForm.projectTypeId = projectTypeId;
  getPersonInfo();
};
// 编辑 id:申报id
const edit = (id) => {
  operateId.value = id;
  nextTick(async () => {
    await getBaseInfoData();
    //基础信息赋值
    assignObj(editForm, baseInfoData.value);
    //日期毫秒数处理成字符串格式
    editForm.birthday = formatDate(editForm.birthday, "YYYY-MM-DD");
    editForm.planStartDate = formatDate(editForm.planStartDate, "YYYY-MM-DD");
    editForm.planEndDate = formatDate(editForm.planEndDate, "YYYY-MM-DD");
  });
};
//点击保存
const save = async (submitType) => {
  try {
    await editFormRef.value?.validate(async (valid) => {
      if (valid) {
        let params = {
          ...editForm,
          submitType,
          isAuditor: isAuditor.value,
          taskId: taskId.value,
          checkstatus: checkStatus.value,
        };
        if (operateId.value) {
          params.id = operateId.value;
        }
        const res = await sbProject(params);
        if (res.code === 200) {
          emit("save-success", res.data.id);
        }
      }
    });
  } catch (error) {
    console.log(error);
  } finally {
    emit("save-ok");
  }
};
defineExpose({ add, edit, save });
//申请经费输入框失去焦点
const applyFeeBlur = () => {
  if (operateId.value && lastApplyFee.value != editForm.applyFee) {
    ElMessage({
      message: `申请经费已经更改，请修改预算明细！`,
      type: "warning",
    });
  }
};
//上传的文件改变
const fileChange = () => {
  const ids = fileList.value.map((item) => {
    const id = item.response ? item.response.data : item.id;
    return id;
  });
  editForm.uploadFileId = ids.join(",");
};
</script>

<style scoped lang="scss"></style>
